package com.ruoyi.iot.config;


import com.ruoyi.iot.service.MqttMessageHandler;
import com.ruoyi.iot.service.MqttMessageHandlerFactory;
import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;


import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 接收mqtt消息入口
 */
@Slf4j
@Service
@EnableAsync(proxyTargetClass = true)
public class MqttMessageListener implements IMqttMessageListener {


    @Resource
    MqttMessageHandlerFactory mqttMessageHandlerFactory;


    @Override
    @Async("mqttTaskExecutor") //可以配置线程池
    public void messageArrived(String topic, MqttMessage message) throws Exception {
      try {
          log.info("Received message on topic: {}" ,topic);
          log.info("Message content: {}" , new String(message.getPayload()));
        // 获取处理类
        MqttMessageHandler mqttMessageHandler = mqttMessageHandlerFactory.getMessageHandler(topic);
        mqttMessageHandler.process(topic,new String(message.getPayload()));
      } catch (Exception e) {
        log.error("处理mqtt消息失败",e);
      }

    }
    
}
